<template>
  <div>
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>
<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 成功读出excel文件的内容
    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      this.tableData = results
      this.tableHeader = header
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      console.log('读出来的excel的内容是', results, header)
      this.tableData = results
      this.tableHeader = header
      const arr = results.map(item => {
        const obj = {}
        header.forEach(ele => {
          obj[mapInfo[ele]] = item[ele]
        })
        return obj
      })
      console.log(arr)
      // 1. 按接口文档要求 对读取的excel数据做格式转换
      const newData = this.transExcel(results, header)
      console.log('转换之后的数据', newData)
      // 2. 调用接口发送请求
      try {
        await importEmployee(newData)
        this.$message.success('导入成功')
        this.$router.push('/employees')
      } catch (err) {
        this.$message.error(err)
      }
    },
    // 对读取的excel数据做格式转换
    transExcel(results, header) {
      console.log('转换之前的数据', results, header)
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      // 处理数据 字段全是中文后端要求是英文
      // 找到所有的中文的key key（所有对象属性名）
      // const zhkeys = Object.keys(results[0])
      // return results.map((item)=>{

      // })

      const zhkeys = Object.keys(results[0])
      console.log('中文的key', zhkeys)
      return results.map((item) => {
        // 创建一个新的对象：它的key是英文的 value是item的值是一致的
        const obj = {}
        zhkeys.forEach((zhkey) => {
          const enkey = mapInfo[zhkey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            obj[enkey] = new Date(formatExcelDate(item[zhkey]))
          } else {
            obj[enkey] = item[zhkey]
          }
        })
        return obj
      })
    }
  }
}
</script>
